package com.wondertek.poms.core.service.impl;

import com.wondertek.poms.common.service.impl.ServiceImpl;
import com.wondertek.poms.core.service.ISpInfoService;
import com.wondertek.poms.dao.po.SpInfo;
import com.wondertek.poms.dao.repo.ISpInfoDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author evan0213
 * @description
 */
@Service
public class SpInfoServiceImpl extends ServiceImpl<SpInfo, Long> implements ISpInfoService {
	@Autowired
	private ISpInfoDao spInfoDao;

	@Override
	public SpInfo deleteLogic(Long id) {
		return null;
	}

	@Override
	public SpInfo merge(SpInfo model) {
		return null;
	}

	@Override
	public Page<SpInfo> findAll(SpInfo spInfo, int page, int rows, String sidx, String sord){
		Specification<SpInfo> specification = getWhereClause(spInfo);

		Sort sort = new Sort("desc".toLowerCase().equals(sord) ?
				Sort.Direction.DESC : Sort.Direction.ASC, sidx);
		Pageable pageable = PageRequest.of(page - 1, rows, sort);

		return spInfoDao.findAll(specification,pageable);
	}

	@Override
	public List<SpInfo> findAll(SpInfo spInfo, String sidx, String sord){
		Specification<SpInfo> specification = getWhereClause(spInfo);

		Sort sort = new Sort("desc".toLowerCase().equals(sord) ?
				Sort.Direction.DESC : Sort.Direction.ASC, sidx);

		return spInfoDao.findAll(specification, sort);
	}

	private Specification<SpInfo> getWhereClause(SpInfo spInfo){
		return (Specification<SpInfo>) (r, q, cb) -> {
			List<Predicate> predicates = new ArrayList<>();
			//内容整合方ID：手工输入，支持精确查找；
			if(spInfo.getSpId() != null){
				predicates.add(cb.equal(r.get("spId"),  spInfo.getSpId()));
			}
			if(spInfo.getName() != null){
				predicates.add(cb.like(r.get("name"), "%" + spInfo.getName()+"%"));
			}
			return cb.and(predicates.toArray(new Predicate[predicates.size()]));
		};
	}
}
